package com.secneo.appshare.activities;

import java.io.ByteArrayOutputStream;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kaixin.connect.Kaixin;
import com.mime.qweibo.JavaScriptInterface;
import com.mime.qweibo.MyWebViewClient;
import com.mime.qweibo.NotifyQWeiboVerify;
import com.renren.api.connect.android.TestConnectButtonListener;
import com.renren.api.connect.android.view.ConnectButton;
import com.renren.api.connect.android.view.RenrenEventListener;
import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.UserInfo;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.ActivityUtil;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.Util;
import com.secneo.appshare.threads.LoginKaixinThread;
import com.secneo.appshare.threads.LoginQWeiboThread;
import com.secneo.appshare.threads.QWeiboGetAccessToken;

public class AccountManagementActivity extends CommonMenuActivity 
									   implements RenrenEventListener, NotifyQWeiboVerify
{
	private LinearLayout bangHeader;
	private ImageView img_bang_user_icon;
	private TextView text_bang_account;
	private TextView text_bang_email;
	
	private LinearLayout sinaHeader;
	private ImageView img_sina_user_icon;
	private TextView text_sina_account;
	private TextView text_sina_logtime;
	private TextView img_sina_logout;
	
	private LinearLayout renrenHeader;
	private ImageView img_renren_user_icon;
	private TextView text_renren_account;
	private TextView text_renren_logtime;
	private TextView img_renren_logout;
	
	private LinearLayout tencentHeader;
	private ImageView img_tencent_user_icon;
	private TextView text_tencent_account;
	private TextView text_tencent_logtime;
	private TextView img_tencent_logout;
	
	private LinearLayout kaixinHeader;
	private ImageView img_kaixin_user_icon;
	private TextView text_kaixin_account;
	private TextView text_kaixin_logtime;
	private TextView img_kaixin_logout;

	private ImageView img_sina_login;
	private ConnectButton connect_renren_login;
	private ImageView img_tencent_login;
	private ImageView img_kaixin_login;
	
	private TextView text_android_id;
	
	private Button modifyPwdBtn ;
	
	private WebView mWebView = null ;
	private WebView mKaixinWebView ;	//for kaixin
	private ProgressDialog mNetProgressBar = null;
	
	public static final int SINA_ACCOUNT_TAG = 1;
	public static final int RENREN_ACCOUNT_TAG = 4;
	public static final int TENCENT_ACCOUNT_TAG = 2;
	public static final int KAIXIN_ACCOUNT_TAG = 3;

	public static final int MSG_GET_BANG_USER_ICON = 101;
	public static final int MSG_GET_SINA_USER_ICON = 102;
	public static final int MSG_GET_RENREN_USER_ICON = 103;
	public static final int MSG_GET_TENCENT_USER_ICON = 104;
	public static final int MSG_GET_KAIXIN_USER_ICON = 106;
	public static final int MSG_GET_BANG_EMAIL = 105;
	Drawable dwSina =null;
	Drawable dwTencent =null;
	Drawable dwRenren =null;
	Drawable dwKaixin =null;
	Drawable dwBang =null;
    String appIconUrl="";
    String emailString="";
    
    private ProgressDialog mModifyPwdProgressBar = null;
    
    //for qweibo
	private String request_token = new String() ;
	private String request_token_secret = new String() ;
	private String verify = new String() ;
	private String access_token = new String() ;
	private String access_token_secret = new String() ;

    public Handler mHandler = new Handler()
	{
    	//TODO 这里腾讯微博登录用到了  1 2 3 4    大家千万不要搞重复了
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case MSG_GET_BANG_USER_ICON:
					img_bang_user_icon.setImageDrawable(dwBang);
					break;
				case MSG_GET_SINA_USER_ICON:
					img_sina_user_icon.setImageDrawable(dwSina);
					break;
				case MSG_GET_RENREN_USER_ICON:
					img_renren_user_icon.setImageDrawable(dwRenren);
					break;
				case MSG_GET_TENCENT_USER_ICON:
					img_tencent_user_icon.setImageDrawable(dwTencent);
					break;
				case MSG_GET_KAIXIN_USER_ICON:
					img_kaixin_user_icon.setImageDrawable(dwKaixin);
					break;
				case MSG_GET_BANG_EMAIL:
					text_bang_email.setText(R.string.label_email_address );
					text_bang_email.append(emailString);
					break;
					
				case 1:		//腾讯微博得到授权的request token
					
					mNetProgressBar.dismiss() ;
					mWebView = (WebView)findViewById(R.id.qweibocWebView);
					mWebView.setVisibility(View.VISIBLE) ;
					//根据id找到相应的WebView
					
					//加载设置
					WebSettings webSetting = mWebView.getSettings();
					//支持ajax
					webSetting.setJavaScriptEnabled(true);
					//支持中文ou
					webSetting.setDefaultTextEncodingName("utf-8");
					//设置允许访问文件数据
					webSetting.setAllowFileAccess(true);
					//设置支持缩放
					webSetting.setBuiltInZoomControls(true);
					//使用WebChromClient功能
					mWebView.setWebChromeClient(new WebChromeClient());
					
					MyWebViewClient webViewClient = new MyWebViewClient() ;
					
					mWebView.setWebViewClient(webViewClient) ;
					
					mWebView.addJavascriptInterface(
							new JavaScriptInterface(AccountManagementActivity.this), 
							"Methods") ;
					
					Bundle bundle = msg.getData() ;
					request_token = bundle.getString(Constants.QWEIBO_TOKEN_ACTION) ;
					request_token_secret = bundle.getString(Constants.QWEIBO_TOKEN_SECRET_ACTION) ;
					
					//加载uri  
					mWebView.loadUrl(
							"http://open.t.qq.com/cgi-bin/authorize?oauth_token="
							+ request_token);
					break ;
				case 2:		//得到access token	
					mNetProgressBar.dismiss() ;
					
					Bundle bundle1 = msg.getData() ;
					access_token = bundle1.getString(
							Constants.QWEIBO_ACCESS_TOKEN_ACTION) ;
					access_token_secret = bundle1.getString(
							Constants.QWEIBO_ACCESS_TOKEN_SECRET_ACTION) ;
					
					Intent intent = new Intent();
					Bundle mBundle = new Bundle(); 
					mBundle.putInt("sns_type", Constants.SNS_INDEX_TENCENT);
					intent.putExtras(mBundle);
					intent.setClass(AccountManagementActivity.this, ChooseUserActivity.class);
					
					Bitmap bmp = BitmapFactory.decodeResource(AccountManagementActivity.this.getResources(), R.drawable.icon);
		            ByteArrayOutputStream baos = new ByteArrayOutputStream();
		            bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
		            byte[] content = baos.toByteArray();
					
					if(!Constants.SWITCH_SINA_CUSTOM){
						RemoteApiImpl rai = new RemoteApiImpl();
						rai.share2QWeiboMsg(AccountManagementActivity.this, 
								Constants.UPLOAD_ACTION_LOGIN, null, 
								content, null, null, null);
					}
					
					bmp.recycle();bmp = null;
					startActivity(intent);
					finish();
					break ;
				case 3:		//登录腾讯微博失败
					Toast.makeText(AccountManagementActivity.this, 
							R.string.label_fb_login_failed, Toast.LENGTH_LONG).show() ;
					mWebView.setVisibility(View.GONE) ;
					mNetProgressBar.dismiss() ;
					break ;
				case 4:
					mWebView.setVisibility(View.GONE) ;
					break ;
				case 5:		//sns账号已经绑定过其他账号，需要提示登出
					if(mWebView != null)
						mWebView.setVisibility(View.GONE) ;
					if(mNetProgressBar != null)
						mNetProgressBar.dismiss() ;
					String nickName = msg.getData().getString("nickName") ;
					String tmp = "操作失败！  "+nickName+"已经存在同步关系，请先解除。";
					ActivityUtil.alert(AccountManagementActivity.this, tmp) ;
					break ;
				case 6:		//开始修改密码，弹出等待对话框
					String prompt = getResources().getString(R.string.txt_modify_pwd_ing) ;
					mModifyPwdProgressBar = mModifyPwdProgressBar.
								show(AccountManagementActivity.this, null , prompt, true) ;
					break ;
				case 7:		//原始密码错误
					if(mModifyPwdProgressBar != null && mModifyPwdProgressBar.isShowing())
						mModifyPwdProgressBar.dismiss() ;
					Toast.makeText(AccountManagementActivity.this, 
							R.string.txt_modify_pwd_faild_pwd_err, 
							Toast.LENGTH_SHORT).show() ;
					break ;
				case 8:		//是该密码成功，取消等待对话框，弹出提示。
					if(mModifyPwdProgressBar != null && mModifyPwdProgressBar.isShowing())
						mModifyPwdProgressBar.dismiss() ;
					Toast.makeText(AccountManagementActivity.this, R.string.txt_modify_pwd_success, 
							Toast.LENGTH_SHORT).show() ;
					break ;
				case 9:		//修改密码失败
					if(mModifyPwdProgressBar != null && mModifyPwdProgressBar.isShowing())
						mModifyPwdProgressBar.dismiss() ;
					Toast.makeText(AccountManagementActivity.this, R.string.txt_modify_pwd_faild, 
							Toast.LENGTH_SHORT).show() ;
					break ;
				case 11:	//修改密码网络错误
					if(mModifyPwdProgressBar != null && mModifyPwdProgressBar.isShowing())
						mModifyPwdProgressBar.dismiss() ;
					Toast.makeText(AccountManagementActivity.this, 
							R.string.txt_modify_pwd_faild_net_err, 
							Toast.LENGTH_SHORT).show() ;
					break ;

				case 201:		//开心网得到授权的request token
					
					if (mNetProgressBar != null) 
					{
						mNetProgressBar.dismiss();
						mNetProgressBar = null; 
					}
					mKaixinWebView = (WebView)findViewById(R.id.kaixinWebView);
					mKaixinWebView.setVisibility(View.VISIBLE) ;
					//根据id找到相应的WebView
					
					//加载设置
					WebSettings webKaixinSetting = mKaixinWebView.getSettings();
					//支持ajax
					webKaixinSetting.setJavaScriptEnabled(true);
					//支持中文ou
					webKaixinSetting.setDefaultTextEncodingName("utf-8");
					//设置允许访问文件数据
					webKaixinSetting.setAllowFileAccess(true);
					//设置支持缩放
					webKaixinSetting.setBuiltInZoomControls(true);
					//使用WebChromClient功能
					
					//加载uri  
					Kaixin kaixin = Kaixin.getInstance();
					String url = Kaixin.KX_AUTHORIZE_URL 
						+ "?oauth_token=" + kaixin.getRequestToken()
						+ "&oauth_client=1";
					mKaixinWebView.loadUrl(url);
					
					LocalStore.getLocaleStoreInstance().setStoredActivity(
							AccountManagementActivity.this);
					
					break ;
					
				default:
					break ;
			}
			super.handleMessage(msg);
		}
	};
	

	public void logout(int loginTag)
	{
		final AlertDialog dialog = new AlertDialog.Builder(this).create();
		LayoutInflater inflater = LayoutInflater.from(this);
		View backupExpandHeader = inflater.inflate(R.layout.sec_opt_scan_stop_dialog, null);
		TextView popTitle = (TextView) backupExpandHeader.findViewById(R.id.popDialogTitle);
		popTitle.setText(this.getResources().getString(R.string.manage_logout));
		TextView popInfo = (TextView) backupExpandHeader.findViewById(R.id.popDialogInfo);
		popInfo.setText(this.getResources().getString(R.string.manage_loginout_alert));
		dialog.show();
		dialog.setContentView(backupExpandHeader);

		if(SINA_ACCOUNT_TAG==loginTag){
			Button okButton = (Button) backupExpandHeader.findViewById(R.id.ButtonOK);
			okButton.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					dialog.dismiss();
					
					sinaHeader.setVisibility(View.GONE);
					img_sina_login.setVisibility(View.VISIBLE);
					
					LocalStore.getLocaleStoreInstance().logoutSinaAccount();
					updateSnsInfo(1);
				}
			});
		}
		if(RENREN_ACCOUNT_TAG==loginTag){
			Button okButton = (Button) backupExpandHeader.findViewById(R.id.ButtonOK);
			okButton.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					dialog.dismiss();
					
					renrenHeader.setVisibility(View.GONE);
					connect_renren_login.setVisibility(View.VISIBLE);
					
					LocalStore.getLocaleStoreInstance().logoutRenrenAccount();
					updateSnsInfo(4);
				}
			});
		}
		if(TENCENT_ACCOUNT_TAG==loginTag){
			Button okButton = (Button) backupExpandHeader.findViewById(R.id.ButtonOK);
			okButton.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					dialog.dismiss();
					
					tencentHeader.setVisibility(View.GONE);
					img_tencent_login.setVisibility(View.VISIBLE);
					
					LocalStore.getLocaleStoreInstance().logoutTencentAccount();
					updateSnsInfo(2);
				}
			});
		}
		if(KAIXIN_ACCOUNT_TAG==loginTag){
			Button okButton = (Button) backupExpandHeader.findViewById(R.id.ButtonOK);
			okButton.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					dialog.dismiss();
					
					kaixinHeader.setVisibility(View.GONE);
					img_kaixin_login.setVisibility(View.VISIBLE);
					
					LocalStore.getLocaleStoreInstance().logoutKaixinAccount();
					updateSnsInfo(3);
				}
			});
		}

		Button cancelButton = (Button) backupExpandHeader.findViewById(R.id.ButtonCancel);
		cancelButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				dialog.dismiss();
			}
		});
	}
	
	
	

	public void SetVerify(String verify){

    	Log.d("qq" , "get verify" + verify) ;
    	
    	String prompt = getResources().getString(R.string.login_ing) ;
    	
		mNetProgressBar = ProgressDialog.show(this, null,prompt ,true);
    	
    	this.verify = verify ; 
    	QWeiboGetAccessToken thread = new QWeiboGetAccessToken(
    			this, mHandler, request_token, request_token_secret, verify) ;
    	thread.start() ;
    	/*Message msg = new Message() ;
    	msg.what = 3 ;
    	mHandler.sendMessage(msg) ;*/
	}
	
    public void onEventLogined(String event){
    	
    	if(LocalStore.getLocaleStoreInstance(this).accountIsActive(3)){
    		return;
    	}
    	
    	if( event.compareTo("renrenlogin")==0 ){
    		
    		LocalStore.getLocaleStoreInstance(this).setRenrenAccountActive();

    		boolean active = LocalStore.getLocaleStoreInstance().accountIsActive(3);
    		//0:bangbang; 1:sina; 2:tencent; 3:renren: 4:kaixin
    		if(active){
    			LocalStore.getLocaleStoreInstance().getRenrenUserInfo();
		  		
	    		Thread loadThread = new Thread()
	    		{		
	    			public void run()
	    			{
	    				try
	    				{
	    					RemoteApiImpl remoteApi = new RemoteApiImpl();
	    					UserInfo ret = null;
	    					String localName = LocalStore.getLocaleStoreInstance().getNickName();
	    					String localIcon = LocalStore.getLocaleStoreInstance().getAvatarName();
	    					if(localName.equals("")){
	    						localName = LocalStore.getLocaleStoreInstance().getRenrenUserNameString();
	    						localIcon = LocalStore.getLocaleStoreInstance().getRenrenPicUrlString();
	    					}
	    					
    						ret = remoteApi.addNewWeiboUser(AccountManagementActivity.this, 4, 
    								LocalStore.getLocaleStoreInstance().getRenrenUidString(), 
    								localName, localIcon);
	    					
							if (ret == null) 
								Log.d("MyTag", "Register renren user failed!");
							else
							{
								if(ret.id.equals(Constants.SNS_HAS_ASSOCIATE) || 
										ret.id == Constants.SNS_HAS_ASSOCIATE){
									
									LocalStore.getLocaleStoreInstance().logoutRenrenAccount();
									
									Message msg = new Message() ;
									Bundle data = new Bundle() ;
				    				msg.what = 5 ;
				    				data.putString("nickName", LocalStore.getLocaleStoreInstance().getRenrenUserNameString()) ;
				    				msg.setData(data) ;
				    				mHandler.sendMessage(msg) ;
				    				return ;
				    			}
				    			
								
								Log.d("MyTag", "Register renren user success!");
								if(ret.id != null && !"".equals(ret.id)){
									LocalStore.getLocaleStoreInstance().setUid(ret.id);
									LocalStore.getLocaleStoreInstance().setAndroidId(ret.androidId);
								}
		    					LocalStore.getLocaleStoreInstance().storeRenrenAccountInfoToLocal();

								LocalStore.getLocaleStoreInstance().setNickName(ret.nick);
								LocalStore.getLocaleStoreInstance().setAvatarName(localIcon);
							}
			    			
			    			Intent intent = new Intent();
							Bundle mBundle = new Bundle();
							mBundle.putInt("sns_type", Constants.SNS_INDEX_RENREN);
							intent.putExtras(mBundle);
			    			intent.setClass(AccountManagementActivity.this, ChooseUserActivity.class);
			    			startActivity(intent);
			    			finish();
							
	    				} catch (Exception ex)
	    				{
	    					ex.printStackTrace();
	    				}
	    			}
	    		};
	    		loadThread.start();
				
    		}
    	}
    }


    public void onEventLogouted(String event){
    	
    	if( event.compareTo("renrenlogout")==0 ){
//        	getUserId();
    	}
    }

    public boolean onRenrenEventClicked(){
    	return true;
    }
	

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.appshare_account_management);
		AppShareApplication.getInstance().addActivity(this);
		bangHeader = (LinearLayout) findViewById(R.id.bang_account_item);
		sinaHeader = (LinearLayout) findViewById(R.id.sina_account_item);
		renrenHeader = (LinearLayout) findViewById(R.id.renren_account_item);
		tencentHeader = (LinearLayout) findViewById(R.id.tencent_account_item);
		kaixinHeader = (LinearLayout) findViewById(R.id.kaixin_account_item);

		if(Constants.SWITCH_SINA_CUSTOM){
			renrenHeader.setVisibility(View.GONE);
			tencentHeader.setVisibility(View.GONE);
			kaixinHeader.setVisibility(View.GONE);
		}

		img_bang_user_icon = (ImageView) findViewById(R.id.img_bang_user_icon);
		img_sina_user_icon = (ImageView) findViewById(R.id.img_sina_user_icon);
		img_renren_user_icon = (ImageView) findViewById(R.id.img_renren_user_icon);
		img_tencent_user_icon = (ImageView) findViewById(R.id.img_tencent_user_icon);
		img_kaixin_user_icon = (ImageView) findViewById(R.id.img_kaixin_user_icon);

		text_bang_account = (TextView) findViewById(R.id.text_bang_account);
		text_sina_account = (TextView) findViewById(R.id.text_sina_account);
		text_renren_account = (TextView) findViewById(R.id.text_renren_account);
		text_tencent_account = (TextView) findViewById(R.id.text_tencent_account);
		text_kaixin_account = (TextView) findViewById(R.id.text_kaixin_account);

		text_bang_email = (TextView) findViewById(R.id.text_bang_email);
		text_sina_logtime = (TextView) findViewById(R.id.text_sina_logtime);
		text_renren_logtime = (TextView) findViewById(R.id.text_renren_logtime);
		text_tencent_logtime = (TextView) findViewById(R.id.text_tencent_logtime);
		text_kaixin_logtime = (TextView) findViewById(R.id.text_kaixin_logtime);

		text_android_id = (TextView) findViewById(R.id.text_android_id);
		
		modifyPwdBtn = (Button) findViewById(R.id.modify_pwd) ;
		modifyPwdBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				modifyPwd() ;
			}
		}) ;
		
		img_sina_login = (ImageView) findViewById(R.id.img_sina_login);
		img_sina_login.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				Bundle bundle=new Bundle();
				bundle.putInt(Constants.EXIT_BEHAVIOUR,Constants.EXIT_BEHAVIOUR_GOTO_ZONE);
				intent.putExtras(bundle);
				intent.setClass(AccountManagementActivity.this, LoginWeiboMethodActivity.class);
				startActivity(intent);
				finish();
				return;
			}
		});
		
		connect_renren_login = (ConnectButton) findViewById(R.id.img_renren_login);
		connect_renren_login.init(Constants.RENREN_BUTTON_ACCOUNT_MANAGEMENT, LocalStore.getLocaleStoreInstance(this).getRenren(), this, this);
		connect_renren_login.setConnectButtonListener(new TestConnectButtonListener());
		if(Constants.SWITCH_SINA_CUSTOM){
			connect_renren_login.setVisibility(View.GONE);
		}
		
		//腾讯微博登录
		img_tencent_login = (ImageView) findViewById(R.id.img_tencent_login);
		img_tencent_login.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				Log.d("qq" , "btn_login_qweibo") ;
				String prompt = getResources().getString(R.string.login_qweibo_ing) ;
				mNetProgressBar = ProgressDialog.show(AccountManagementActivity.this, null,prompt ,true);
				
				LoginQWeiboThread thread = new LoginQWeiboThread(AccountManagementActivity.this, mHandler) ;
				thread.start() ;
			}
		});
		if(Constants.SWITCH_SINA_CUSTOM){
			img_tencent_login.setVisibility(View.GONE);
		}

		
		//开心网登录
		img_kaixin_login = (ImageView) findViewById(R.id.img_kaixin_login);
		img_kaixin_login.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				Log.d("MyTag" , "btn_login_kaixin");
				LoginKaixinThread kaixinThread = new LoginKaixinThread(AccountManagementActivity.this, mHandler);
				kaixinThread.start();
			}
		});
		if(Constants.SWITCH_SINA_CUSTOM){
			img_kaixin_login.setVisibility(View.GONE);
		}


		img_sina_logout = (TextView) findViewById(R.id.img_sina_logout);
		img_sina_logout.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				logout(SINA_ACCOUNT_TAG);
			}
		});

		img_renren_logout = (TextView) findViewById(R.id.img_renren_logout);
		img_renren_logout.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				logout(RENREN_ACCOUNT_TAG);
			}
		});

		img_tencent_logout = (TextView) findViewById(R.id.img_tencent_logout);
		img_tencent_logout.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				logout(TENCENT_ACCOUNT_TAG);
			}
		});

		img_kaixin_logout = (TextView) findViewById(R.id.img_kaixin_logout);
		img_kaixin_logout.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				logout(KAIXIN_ACCOUNT_TAG);
			}
		});
		

		loadBangItem();
		loadSinaItem();
		if(!Constants.SWITCH_SINA_CUSTOM){
			loadRenrenItem();
			loadTencentItem();
			loadKaixinItem();
		}


		Button returnButton=(Button)findViewById(R.id.img_ret);
		returnButton.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		ImageView homeButton=(ImageView)findViewById(R.id.img_home);
		homeButton.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent();
				intent.setClass(AccountManagementActivity.this, MainActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				AccountManagementActivity.this.startActivity(intent);
				finish();
			}
		});

	}
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}


	private void loadBangItem()
	{
		boolean active = LocalStore.getLocaleStoreInstance().accountIsActive(0);
		//0:bangbang; 1:sina; 2:tencent; 3:renren: 4:kaixin
		
		text_bang_account.setText(R.string.label_account );
		text_bang_account.append(LocalStore.getLocaleStoreInstance().getNickName());
		
		text_android_id.setText(R.string.label_android_id );
		String aid = LocalStore.getLocaleStoreInstance().getAndroidId() ;
		text_android_id.append(aid);
		
		
		loadUserEmail();
		loadBangUserIcon();
	}


	private void loadSinaItem()
	{
		boolean active = LocalStore.getLocaleStoreInstance().accountIsActive(1);
		//0:bangbang; 1:sina; 2:tencent; 3:renren: 4:kaixin
		if(active){
			LocalStore.getLocaleStoreInstance().getSinaUserInfo();
			sinaHeader.setVisibility(View.VISIBLE);
			img_sina_login.setVisibility(View.GONE);
			//0:anonymous; 1:bangbang; 2:sina; 3:tencent; 4:renren: 5:kaixin
			
			text_sina_account.setText(R.string.label_account );
			text_sina_account.append(LocalStore.getLocaleStoreInstance().getAccountScreenName(Constants.SNS_INDEX_SINA));
			text_sina_logtime.setText(R.string.label_login_time );
			text_sina_logtime.append(LocalStore.getLocaleStoreInstance().getLastLoginTimeString(Constants.SNS_INDEX_SINA));
			loadAccountNameAndIcon(MSG_GET_SINA_USER_ICON, Constants.SNS_INDEX_SINA);
		}
		else{
			img_sina_login.setVisibility(View.VISIBLE);
		}
	}

	private void loadRenrenItem()
	{
		boolean active = LocalStore.getLocaleStoreInstance().accountIsActive(3);
		//0:bangbang; 1:sina; 2:tencent; 3:renren: 4:kaixin
		if(active){
			LocalStore.getLocaleStoreInstance().getRenrenUserInfo();
			renrenHeader.setVisibility(View.VISIBLE);
			connect_renren_login.setVisibility(View.GONE);
			//0:anonymous; 1:bangbang; 2:sina; 3:tencent; 4:renren: 5:kaixin
			
			text_renren_account.setText(R.string.label_account );
			text_renren_account.append(LocalStore.getLocaleStoreInstance().getAccountScreenName(Constants.SNS_INDEX_RENREN));
			text_renren_logtime.setText(R.string.label_login_time );
			text_renren_logtime.append(LocalStore.getLocaleStoreInstance().getLastLoginTimeString(Constants.SNS_INDEX_RENREN));
			loadAccountNameAndIcon(MSG_GET_RENREN_USER_ICON, Constants.SNS_INDEX_RENREN);
		}
		else{
			connect_renren_login.setVisibility(View.VISIBLE);
		}
	}

	private void loadTencentItem()
	{
		try
		{
			boolean active = LocalStore.getLocaleStoreInstance().accountIsActive(2);
			Log.d("qq" , "loadTencentItem active = " + active) ;
			//0:bangbang; 1:sina; 2:tencent; 3:renren: 4:kaixin
			if(active){
				LocalStore.getLocaleStoreInstance().getTencentUserInfo();
				tencentHeader.setVisibility(View.VISIBLE);
				img_tencent_login.setVisibility(View.GONE);
				
				text_tencent_account.setText(R.string.label_account );
				text_tencent_account.append(LocalStore.getLocaleStoreInstance().getAccountScreenName(Constants.SNS_INDEX_TENCENT));
				text_tencent_logtime.setText(R.string.label_login_time );
				text_tencent_logtime.append(LocalStore.getLocaleStoreInstance().getLastLoginTimeString(Constants.SNS_INDEX_TENCENT));
				loadAccountNameAndIcon(MSG_GET_TENCENT_USER_ICON, Constants.SNS_INDEX_TENCENT);
			}
			else{
				img_tencent_login.setVisibility(View.VISIBLE);
			}
			
		}catch (Exception ex)
		{
			Log.d("MyTag", "loadTencentItem error = "+ex.getMessage());
			ex.printStackTrace();
		}
	}

	private void loadKaixinItem()
	{
		try
		{
			boolean active = LocalStore.getLocaleStoreInstance().accountIsActive(4);
			//0:bangbang; 1:sina; 2:tencent; 3:renren: 4:kaixin
			if(active){
				LocalStore.getLocaleStoreInstance().getKaixinUserInfo();
				kaixinHeader.setVisibility(View.VISIBLE);
				img_kaixin_login.setVisibility(View.GONE);
				
				text_kaixin_account.setText(R.string.label_account );
				text_kaixin_account.append(LocalStore.getLocaleStoreInstance().getAccountScreenName(Constants.SNS_INDEX_KAIXIN));
				text_kaixin_logtime.setText(R.string.label_login_time );
				text_kaixin_logtime.append(LocalStore.getLocaleStoreInstance().getLastLoginTimeString(Constants.SNS_INDEX_KAIXIN));
				loadAccountNameAndIcon(MSG_GET_KAIXIN_USER_ICON, Constants.SNS_INDEX_KAIXIN);
			}
			else{
				img_kaixin_login.setVisibility(View.VISIBLE);
			}
			
		}catch (Exception ex)
		{
			Log.d("MyTag", "loadKaixinItem error = "+ex.getMessage());
			ex.printStackTrace();
		}
	}

	private void loadAccountNameAndIcon(int accountTag, int snsType)
	{
		String user_image=LocalStore.getLocaleStoreInstance().getAccountProfileImageURL(snsType);
		UserAppIconThread userAppIconThread = new UserAppIconThread(this, mHandler,user_image,accountTag);
		userAppIconThread.start();
	}

	private void loadUserEmail()
	{
		EmailThread emailThread = new EmailThread(this, mHandler);
		emailThread.start();
	}

	private void updateSnsInfo(int snsType)
	{
		DestroySnsThread destroySnsThread = new DestroySnsThread(this, mHandler, snsType);
		destroySnsThread.start();
	}
	
	

	private void loadBangUserIcon()
	{
		String user_image=LocalStore.getLocaleStoreInstance().getAvatarName();
		if(!"".equals(user_image)&&user_image!=null)
		{
			UserAppIconThread userAppIconThread = new UserAppIconThread(this, mHandler, user_image, MSG_GET_BANG_USER_ICON);
			userAppIconThread.start();
			
		}
		else
		{
			if("".equals(user_image) || user_image==null)
				return;
		}
	}
	

	/* 退出处理 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			if (View.VISIBLE==mKaixinWebView.getVisibility())
			{
				mKaixinWebView.setVisibility(View.GONE);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	
	

	public class UserAppIconThread extends Thread 
	{
		private Context ctx;
		private Handler handler;
		private List<ApplicationInfo> otherUserApp;
		private String appIconurl;
		private int accountTag;
		
		public UserAppIconThread(Context ctx, Handler handler,String appIconurl, int accountTag) 
		{
			this.ctx = ctx;
			this.handler = handler;
			this.appIconurl=appIconurl;
			this.accountTag=accountTag;
		}
		
		public List<ApplicationInfo>  getUserApps() 
		{
			return otherUserApp;
		}
		
		public void run() 
		{
			try 
			{
				Drawable dws = null;
				if(appIconurl.contains("buildin"))
					dws = Util.getDrawableFromAsset(ctx, appIconurl);
				else
					dws = Util.getDrawableFromCache(ctx, appIconurl);
				switch(accountTag)
				{
					case MSG_GET_BANG_USER_ICON:
						dwBang=dws;
						break;
					case MSG_GET_SINA_USER_ICON:
						dwSina=dws;
						break;
					case MSG_GET_TENCENT_USER_ICON:
						dwTencent=dws;
						break;
					case MSG_GET_RENREN_USER_ICON:
						dwRenren=dws;
						break;
					case MSG_GET_KAIXIN_USER_ICON:
						dwKaixin=dws;
						break;
					default:
						break;
				}
				Message msg = new Message();
				msg.what = accountTag;
				handler.sendMessage(msg);
				
			} catch(Exception ex) {
				ex.printStackTrace();
			}
		}
	}
	
	public class EmailThread extends Thread 
	{
		private Context ctx;
		private Handler handler;
		public EmailThread(Context ctx, Handler handler) 
		{
			this.ctx = ctx;
			this.handler = handler;
		}
		
		public void run() 
		{
			try 
			{
				RemoteApiImpl remoteApi = new RemoteApiImpl();
				String userId = LocalStore.getLocaleStoreInstance().getUid();
				emailString = remoteApi.getEmail(ctx, userId);
				Message msg = new Message();
				msg.what = MSG_GET_BANG_EMAIL;
				handler.sendMessage(msg);
				
			} catch(Exception ex) {
				ex.printStackTrace();
			}
		}
	}
	

	public class DestroySnsThread extends Thread 
	{
		private Context ctx;
		private Handler handler;
		private int snsType;
		public DestroySnsThread(Context ctx, Handler handler, int snsType) 
		{
			this.ctx = ctx;
			this.handler = handler;
			this.snsType = snsType;
		}
		
		public void run() 
		{
			try 
			{
				RemoteApiImpl remoteApi = new RemoteApiImpl();
				boolean result = remoteApi.destroySNSAccount(AccountManagementActivity.this, 
						LocalStore.getLocaleStoreInstance().getUid(),
						snsType
						);
				
			} catch(Exception ex) {
				ex.printStackTrace();
			}
		}
	}
	
	private void modifyPwd() {
		LayoutInflater inflater = LayoutInflater.from(this);
		final View textEntryView = inflater.inflate(
				R.layout.modify_pwd_dlg_layout, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.txt_modify_pwd);
		builder.setView(textEntryView);
		final EditText oldPwdEt = (EditText)textEntryView.
		findViewById(R.id.old_pwd) ;
		final EditText newPwdEt1 = (EditText)textEntryView.
				findViewById(R.id.new_pwd1) ;
		final EditText newPwdEt2 = (EditText)textEntryView.
				findViewById(R.id.new_pwd2) ;
		builder.setPositiveButton(R.string.alert_dialog_button_ok,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {						
						
						final String newPwd1 = newPwdEt1.getText().toString() ;
						String newPwd2 = newPwdEt2.getText().toString() ;
						final String oldPwd = oldPwdEt.getText().toString() ;
						if(ActivityUtil.isEmpty(newPwdEt1 , newPwdEt2 , oldPwdEt)){
							Toast.makeText(AccountManagementActivity.this, 
									R.string.txt_pwd_null_prompt, Toast.LENGTH_SHORT).show() ;
							modifyPwd() ;
							return ;
						}
						if(newPwd1.length() < 6 || newPwd2.length() < 6 ||
								oldPwd.length() < 6){
							Toast.makeText(AccountManagementActivity.this, 
									R.string.txt_pwd_less_six_prompt, Toast.LENGTH_SHORT).show() ;
							modifyPwd() ;
							return ;
						}
						if(newPwd1.equals(newPwd2)){
							Message msg1 = new Message() ;
							msg1.what = 6 ;
							mHandler.sendMessage(msg1) ;
							Thread modifyPwdThread = new Thread(){
								public void run(){
									RemoteApiImpl rai = new RemoteApiImpl() ;
									String retStr = rai.modifyUserPassword(
											AccountManagementActivity.this, 
											LocalStore.getLocaleStoreInstance(AccountManagementActivity.this).getUid(), 
											oldPwd, newPwd1) ;
									Message msg = new Message() ;
									if(retStr.equals("ok")){
										msg.what = 8 ;
										mHandler.sendMessage(msg) ;
									} else if(retStr.equals("badpassword")){
										msg.what = 7 ;
										mHandler.sendMessage(msg) ;
									} else if(retStr.equals("other")){
										msg.what = 9 ;
										mHandler.sendMessage(msg) ;
									} else if(retStr.equals("net_error")){
										msg.what = 11 ;
										mHandler.sendMessage(msg) ;
									}
								}
							} ;
							modifyPwdThread.start() ;
						} else {
							Toast.makeText(AccountManagementActivity.this, 
									R.string.txt_pwd_dif , Toast.LENGTH_SHORT).show() ;
							newPwdEt1.setText("") ;
							newPwdEt2.setText("") ;
							modifyPwd() ;
						}		
					}
				});
		
		builder.setNegativeButton(R.string.alert_dialog_button_cancel, null);
		builder.create().show() ;
	}
}
